package com.ai.smlcore.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class CSVUtil {
	public static boolean isMobileNumber(String mobiles) {
		return Pattern.compile("^1\\d{10}").matcher(mobiles).matches();
	}
	
	/**
	 * 设置模板错误信息
	 * @author yangyanli
	 * @param num
	 * @param fileName
	 * @param linked
	 */
	public void setErrorInfo(int num,String fileName,Map<String, String> linked){
		linked.clear();
		linked.put("flag", "false");
		linked.put("row", num+"");
		linked.put("FILE_NM", fileName);
		linked.put("ERROR_RSN_DESC", num + "模版错误");
		linked.put("ERROR_DESC", "目标客户模版不正确,第一行必须包含“用户号码”字段");
	}
	
	public List<Map<String, String>> readCSV(InputStream inputStream, String fileName) throws IOException {

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
		String lineTxt = null;
		List<Map<String, String>> list = new LinkedList<Map<String, String>>();
		List<String> tableHead = new ArrayList<String>();//存放内容不确定的表头信息
		// 定义一个行号 初始化为0
		int num = 0;
		while ((lineTxt = bufferedReader.readLine()) != null) {
			num = num + 1;//csv文件行号从1开始
			if(lineTxt.length()==0){
				continue;
			}
			Map<String, String> linked = new HashMap<String, String>();
			// 行号小于等于1就跳出单词循环
			if (num <= 1) {
				if(lineTxt.contains(",")){//该类型文件用","对各个列进行分隔;第一行为表头
					String[] colons = lineTxt.split(",");
					if(!(colons[0].contains("号码"))){
						setErrorInfo(num,fileName,linked);
						break;
					}else{
						tableHead = Arrays.asList(colons);
					}
					
				}else{
					if(!(lineTxt.contains("号码"))){
						setErrorInfo(num,fileName,linked);
						break;
					}else{
						tableHead = Arrays.asList(lineTxt);
					}
				}
				continue;
			}

			String[] s = lineTxt.split(",",-1);
			if(s.length == tableHead.size()){//所填数据的个数和表头个数一致
				if(!isMobileNumber(s[0].toString())){
					linked.clear();
					linked.put("flag", "false");
					linked.put("row", num+"");
					linked.put("FILE_NM", fileName);
					linked.put("ERROR_RSN_DESC", num + "行,手机格式错误");
					linked.put("ERROR_DESC", "手机格式错误");
					break;
				}else{
					linked.put("flag", "true");
					linked.put("RESV_MOBNUM", s[0].trim());
					linked.put("LIN_CUST_NM", "");
					
					StringBuilder custExtdData = new StringBuilder();//用于保存所有的附属信息，（key1：value1；key2：value2...）
					
					for(int i = 1;i < tableHead.size() - 1;i++){//不需要保存用户号码
						s[i] = ("".equals(s[i].trim())?"null":s[i].trim());//如果该字段是空，那么转存null
						custExtdData.append(tableHead.get(i) + ":" + s[i].trim() + ",");
					}
					s[tableHead.size() - 1] = ("".equals(s[tableHead.size() - 1].trim())?"null":s[tableHead.size() - 1].trim());//如果该字段是空，那么转存null
					custExtdData.append(tableHead.get(tableHead.size() - 1) + ":" + s[tableHead.size() - 1].trim());
					
					linked.put("CUST_EXTD_DATA", custExtdData.toString());
					list.add(linked);
				}
			}else{
				linked.put("flag", "false");
				linked.put("row", num+"");
				linked.put("FILE_NM", fileName);
				linked.put("ERROR_RSN_DESC", num + "行解析错误");
				linked.put("ERROR_DESC", "手机号不能为空,每一行只能有一个用户信息");
			}
			
		}
		return list;
	}
}
